package com.example.wyy;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.FileObserver;
import android.os.Handler;
import android.provider.SyncStateContract;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.AdapterViewFlipper;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

import adapter.FliperAdapter;
import adapter.GridViewAdapter;
import adapter.ListViewAdapter;
import entiy.MusicInfo;
import entiy.Rec;
import util.MusicUtil;

public class MainActivity extends AppCompatActivity  implements View.OnClickListener, AdapterView.OnItemClickListener {
    private int []flipImg = new int[] {
        R.mipmap.ee,R.mipmap.ff,R.mipmap.gg
    };
    private AdapterViewFlipper flipper;
    private MediaPlayer mediaPlayer;
    private ImageView bottom_recommend;
    private GridView gridView;
    private RelativeLayout play;
    private ImageView bottom_img;
    private ImageView main_play_pause;
    private ListView music_listview;
    private ListViewAdapter listViewAdapter;
    private TextView bottom_title;
    private TextView bottom_artlist;
    List<MusicInfo> defaultInfo;
    private SeekBar progressBar_bottom;
    private ImageView test_img;
    private List<Rec> recList;
    private ImageView recommend;
    int total_time;
    int current_time;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if ( ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);

        }
        if (ContextCompat.checkSelfPermission(this,Manifest.permission.WAKE_LOCK) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WAKE_LOCK},2);
        }

        GridViewAdapter gridadapter = new GridViewAdapter(this, Rec.getDefautRec());
        flipper = findViewById(R.id.flipper);
        gridView = findViewById(R.id.grid_view);
        gridView.setAdapter(gridadapter);
        play = findViewById(R.id.play);
        bottom_img = findViewById(R.id.bottom_img);
        main_play_pause = findViewById(R.id.main_play_pause);
        music_listview = findViewById(R.id.music_list);
        bottom_title = findViewById(R.id.bottom_title);
        bottom_artlist = findViewById(R.id.bottom_artlist);
        test_img = findViewById(R.id.test_img);
        progressBar_bottom = findViewById(R.id.progress_bottom);
        recommend = findViewById(R.id.recommend);
        recList = Rec.getDefautRec();

        play.setOnClickListener(this);
        bottom_img.setOnClickListener(this);
        main_play_pause.setOnClickListener(this);
        music_listview.setOnItemClickListener(this);
        recommend.setOnClickListener(this);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("TAG", "onItemClick: " + id );
                Rec rec = recList.get((int) id);
                Intent intent = new Intent(MainActivity.this, MusicListActivity.class);
                intent.putExtra("desc",rec.getDesc());
                intent.putExtra("pic",rec.getImg());

                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);

            }
        });
        try {
            listViewAdapter = new ListViewAdapter(this, MusicInfo.getDefaultInfo());
            music_listview.setAdapter(listViewAdapter);
        } catch (Exception e) {
            e.printStackTrace();
        }



        bottom_recommend = findViewById(R.id.bottom_recommend);
        bottom_recommend.setOnClickListener(this);

        FliperAdapter adapter = new FliperAdapter(this, flipImg);
        flipper.setAdapter(adapter);
        flipper.startFlipping();

        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Log.e("TAG", "onError: " + "error" );
                return true;
            }
        });
        progressBar_bottom.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_color));
    }



    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.bottom_recommend){
            bottom_recommend.setImageResource(R.mipmap.cyy);
        }else if (v.getId() == R.id.play || v.getId() == R.id.bottom_img){
            current_time = mediaPlayer.getCurrentPosition()/1000;

            Intent intent = new Intent(MainActivity.this,playActivity.class);

            intent.putExtra("title",bottom_title.getText().toString());
            intent.putExtra("artlist", bottom_artlist.getText().toString());
            Drawable drawable = bottom_img.getDrawable();

            bottom_img.setDrawingCacheEnabled(true);
            Bitmap bitmap = Bitmap.createBitmap(bottom_img.getDrawingCache());
            //test_img.setImageBitmap(bitmap);
            intent.putExtra("bitmap",bitmap);
            intent.putExtra("total_time",total_time);
            intent.putExtra("current_time",current_time);
            Log.e("TAG", "onClick: " + total_time);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);

            bottom_img.setDrawingCacheEnabled(false);
        }else if (v.getId() == R.id.main_play_pause){

            if (mediaPlayer.isPlaying()){
                mediaPlayer.pause();
                main_play_pause.setImageResource(R.mipmap.d6t);
            }else {
                mediaPlayer.start();
                main_play_pause.setImageResource(R.mipmap.d2v);
            }
        }else if (v.getId() == R.id.recommend) {
                Intent intent = new Intent(MainActivity.this, DayRecommendActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        final List<String> list = MusicUtil.readDirectory();

        //Log.e("TAG", "onItemClick: "+ list.get(position) );
        try {
            defaultInfo = MusicInfo.getDefaultInfo();
            mediaPlayer.reset();
            mediaPlayer.setDataSource(list.get(position));
            //Log.e("TAG", "onItemClick: "+ list.get(position));
            // mediaPlayer.prepare();
            //mediaPlayer.prepare();

            mediaPlayer.prepare();
            progressBar_bottom.setMax(mediaPlayer.getDuration() / 1000);
            total_time = mediaPlayer.getDuration()/1000;
            Log.e("TAG", "onItemClick: " + total_time );
           // Log.e("TAG", "onItemClick: " + mediaPlayer.getDuration() / 1000 );
            mediaPlayer.start();

            handler.post(runnable);
            main_play_pause.setImageResource(R.mipmap.d2v);
            bottom_img.setImageBitmap(defaultInfo.get(position).getBitmap());
            bottom_title.setText(defaultInfo.get(position).getTitle());
            bottom_artlist.setText(defaultInfo.get(position).getArtlist());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null){
            mediaPlayer.release();
        }
    }
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            progressBar_bottom.setProgress(mediaPlayer.getCurrentPosition() / 1000);
            handler.postDelayed(this,1000);
        }
    };

}